package com.cl.it.pool;

import com.cl.it.mbg.entity.AccessPool;
import com.cl.it.exception.BizException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.util.HashMap;
import java.util.Map;

public class AccessIndirectConnectionManager {
    private static Map<String, Session> sessions = new HashMap<>();

    public static synchronized void connect(AccessPool accessPool) {
        if (accessPool.getActive() != 1) {
            return;
        }
        try {
            JSch sch = new JSch();
            if (null != accessPool.getSshKnownHosts() && !"".equals(accessPool.getSshKnownHosts())) {
                sch.setKnownHosts(accessPool.getSshKnownHosts());
            }
            if (null != accessPool.getSshKeyPath() && !"".equals(accessPool.getSshKeyPath())) {
                sch.addIdentity(accessPool.getSshKeyPath());
            }
            Session session = sch.getSession(accessPool.getUsername(), accessPool.getHost(), accessPool.getPort());
            session.setConfig("StrictHostKeyChecking", "no");
            if (null != accessPool.getPassword() && !"".equals(accessPool.getPassword())) {
                session.setPassword(accessPool.getPassword());
            }
            session.connect();
            session.setPortForwardingL(accessPool.getFromHost(), accessPool.getFromPort(), accessPool.getToHost(), accessPool.getToPort());
            sessions.put(accessPool.getId(), session);
        } catch (Exception e) {
            throw new BizException(String.format("session create faild. id=%s", accessPool.getId()));
        }
    }

    public static synchronized void disconnect(AccessPool pool) {
        if (!sessions.containsKey(pool.getId())) {
            return;
        }
        sessions.get(pool.getId()).disconnect();
        sessions.remove(pool.getId());
    }

    public static Map<String, Session> getSessions() {
        return sessions;
    }
}
